package com.colin.aiyi.ui.Home.mine;

import android.content.Intent;
import android.view.View;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.colin.aiyi.R;
import com.colin.aiyi.app.Constant;
import com.colin.aiyi.app.MyApp;
import com.colin.aiyi.dao.ImpxUtils.ImpDiscourseListLke;
import com.colin.aiyi.dao.ImpxUtils.ImpDoLike;
import com.colin.aiyi.dao.ImpxUtils.ImpDoWatch;
import com.colin.aiyi.dao.ImpxUtils.ImpMsgDelete;
import com.colin.aiyi.dao.ImpxUtils.ImpMsgList;
import com.colin.aiyi.dao.ImpxUtils.ImpSayLikeList;
import com.colin.aiyi.dao.ImpxUtils.ImpSayWatchList;
import com.colin.aiyi.entity.BaseRequest;
import com.colin.aiyi.entity.response.BaseResponse;
import com.colin.aiyi.entity.DataEntity;
import com.colin.aiyi.entity.response.LoginResponse;
import com.colin.aiyi.entity.MsgEntity;
import com.colin.aiyi.entity.response.MsgResponse;
import com.colin.aiyi.entity.User;
import com.colin.aiyi.entity.response.WatchResponse;
import com.colin.aiyi.entity.YiJuAndYiShuoEntity;
import com.colin.aiyi.entity.response.YiJuAndYiShuoResponse;
import com.colin.aiyi.presenter.AbsP;
import com.colin.aiyi.ui.AcMsgDetails;
import com.colin.aiyi.ui.login.LoginAc;
import com.colin.aiyi.ui.pay.PayAc;
import com.colin.aiyi.ui.sayDetail.TeacherSayDetailsActivity;
import com.colin.aiyi.utils.MusicUtil;
import com.colin.aiyi.utils.NetUtils;
import com.colin.aiyi.utils.SharePreferenceUtil;
import com.colin.aiyi.view.ShowMsgUtil;

import java.util.List;

/**
 * Created by hl on 2017/6/6.
 */

public class ImpPHome extends AbsP {
    IViewHome iViewHome;
    private String contentType;
    private int pageNum;
    private boolean pullMore=false;
    private int totalCount;
    private String lastType=Constant.TAB_TYPE_SAY_WACTH;
    BaseRequest request=new BaseRequest();
    private User user= SharePreferenceUtil.getObject(MyApp.getInstance().getApplicationContext(),User.class);
    private BaseQuickAdapter childAdapter;
    private int childPosition;
    private YiJuAndYiShuoEntity childYiShuoEntity;

    /********
     * 获取一说列表
     * @param //pageNum  目标页面
     * @param //cType  类型
     */

    public void getAllT(BaseRequest request) {
        this.contentType=request.getOrderType();
        this.request=request;
        switch (contentType)
        {
            case Constant.TAB_TYPE_SAY_WACTH:
                iService=new ImpSayWatchList();
                break;
            case Constant.TAB_TYPE_SAY_LIKE:
                iService=new ImpSayLikeList();
                break;
            case Constant.TAB_TYPE_LIKE:
                iService=new ImpDiscourseListLke();
                break;
            case Constant.TAB_TYPE_MSG:
                iService=new ImpMsgList();
                break;
        }
        iService.getObject(this,request);
      //  ShowMsgUtil.showLoadingDialog(iViewHome.getContext());
    }

    public ImpPHome(IViewHome iViewHome) {
        this.iViewHome = iViewHome;
    }

    @Override
    public void onSuccess(Object t) {
        ShowMsgUtil.hideLoadingDialog();
        if (t instanceof WatchResponse){
            if (((WatchResponse) t) .getCode()==200)// 观看结果集
            {
                MusicUtil.getInstance().setMusicTitle(childYiShuoEntity.getTitle());
                MusicUtil.getInstance().setMusicPic(Constant.BASE_URL+childYiShuoEntity.getUrl());;
                MusicUtil.getInstance().setDataSource( childYiShuoEntity.getVoiceUrl()+((WatchResponse) t).getData().getToken());
                watchAddNum(childAdapter,childYiShuoEntity,childPosition);
            }
            else if (((LoginResponse) t).getMessage().equals("你已经点过赞")){
                childYiShuoEntity.setLikeCountActive(1);
                childAdapter.notifyItemChanged(childPosition);
            }
            else {
                showMsg(((WatchResponse) t).getMessage());
            }
        }

           if (t instanceof MsgResponse)
           {
               if (((MsgResponse) t).getCode()==200)
               {
                   bindMsg((MsgResponse) t);
               }else {
                   sendMsgToView(((BaseResponse)t));
               }
           }

           if (t instanceof YiJuAndYiShuoResponse){
               if (((YiJuAndYiShuoResponse) t).getCode()==200)
               {
                   if (((YiJuAndYiShuoResponse) t).getMsgType()==(Constant.CODE_SAY_sayLikeList)||
                           ((YiJuAndYiShuoResponse) t).getMsgType()==  Constant.CODE_DISCOURSE_discourseLikeList){
                       try {
                           List<YiJuAndYiShuoEntity>  items=((YiJuAndYiShuoResponse) t).getData().getItems();
                           for (YiJuAndYiShuoEntity item : items) {
                               item.setLikeCountActive(1);
                           }
                       } catch (Exception e) {
                           e.printStackTrace();
                       }
                   }
                   dataPreprocess((YiJuAndYiShuoResponse) t);
               }else {
                   sendMsgToView(((BaseResponse)t));
               }
           }

           if (t instanceof LoginResponse){// like结果集
               if (((LoginResponse) t).getCode()==200){
                   if (childYiShuoEntity.getLikeCountActive()==1){
                       childYiShuoEntity.setLikeCountActive(0);
                       childYiShuoEntity.setLikeCount(childYiShuoEntity.getLikeCount()-1);
                   }else {
                       childYiShuoEntity.setLikeCountActive(1);
                       childYiShuoEntity.setLikeCount(childYiShuoEntity.getLikeCount()+1);
                   }
                   childAdapter.notifyItemChanged(childPosition);
               }else {
                   showMsg(((LoginResponse) t).getMessage());
               }
           }

    }
    private void dataPreprocess(YiJuAndYiShuoResponse d){
        DataEntity dataEntity = d.getData();
        totalCount=dataEntity.getCount();
        List<YiJuAndYiShuoEntity> list = dataEntity.getItems();
        if (!lastType.equals(contentType))
        {
            pullMore=false;
        }
        lastType=contentType;
        if (pullMore)
        {
            iViewHome.pullMoreComlite();
        }else {
            iViewHome.getData().clear();
            iViewHome.refreshComplite();
        }
        if (list!=null&&list.size()>0)
        {
            iViewHome.getData().addAll(list);
        }else {
            iViewHome.refreshNoData();
        }
    }


    private void bindMsg(MsgResponse d){
        MsgEntity dataEntity = d.getData();
        totalCount=dataEntity.getCount();
        List<MsgEntity.ItemsBean> list = dataEntity.getItems();
        if (!lastType.equals(contentType))
        {
            pullMore=false;
        }
        lastType=contentType;
        if (pullMore)
        {
            iViewHome.pullMoreComlite();
        }else {
            iViewHome.getData().clear();
            iViewHome.refreshComplite();
        }
        if (list!=null&&list.size()>0)
        {
            iViewHome.getData().addAll(list);
        }else {
            iViewHome.refreshNoData();
        }
        iViewHome.allMsgRead();
    }

    @Override
    public void onRefresh() {
        super.onRefresh();
        pullMore=false;
        request.setPageNum(1);
        getAllT(request);
    }

    @Override
    public void onLoadMoreRequested() {
        if (iViewHome.getData().size() < totalCount) {
            pullMore=true;
            request.setPageNum(request.getPageNum()+1);
            getAllT(request);
        } else {
            iViewHome.pullMoreNoMore();
        }
    }
    private void watchAddNum(BaseQuickAdapter adapter,YiJuAndYiShuoEntity yiShuoEntity, int position){
        yiShuoEntity.setWatchCount(yiShuoEntity.getWatchCount()+1);
        yiShuoEntity.setWatchCountActive(1);
        adapter.notifyItemChanged(position);
    }


    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        super.onItemClick(adapter, view, position);
        switch (contentType)
        {
            case Constant.TAB_TYPE_SAY_WACTH:
            case Constant.TAB_TYPE_SAY_LIKE:
                Intent intent = new Intent(iViewHome.getContext(), TeacherSayDetailsActivity.class);
                String id=((YiJuAndYiShuoEntity) adapter.getData().get(position)).getId()+"";
                intent.putExtra("id",id);
                iViewHome.startNextAc(intent);
                break;
            case Constant.TAB_TYPE_MSG:
                Intent intent2 = new Intent(iViewHome.getContext(), AcMsgDetails.class);
                MsgEntity.ItemsBean msgEntity= (MsgEntity.ItemsBean) adapter.getData().get(position);
                intent2.putExtra("isRead",msgEntity.isIsRead());
                intent2.putExtra("id",msgEntity.getId());
                intent2.putExtra("title",msgEntity.getTitle());
                intent2.putExtra("content",msgEntity.getContent());
                intent2.putExtra("pushTime",msgEntity.getPushTime());
                iViewHome.startNextAc(intent2,1);
                msgEntity.setIsRead(true);
                adapter.notifyItemChanged(position);
                iViewHome.allMsgRead();
                break;
        }
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        super.onItemChildClick(adapter, view, position);
        childAdapter=adapter;
        childPosition=position;
        if (adapter.getData().get(position) instanceof YiJuAndYiShuoEntity){
            childYiShuoEntity = (YiJuAndYiShuoEntity) adapter.getData().get(position);
        }
        switch (view.getId()){
            case R.id.button_delete:
                if (adapter.getData().get(position) instanceof MsgEntity.ItemsBean){
                    deleteMsg(adapter,position);
                    return;
                }
                break;
            case R.id.msg_root_parent:
                Intent intent2 = new Intent(iViewHome.getContext(), AcMsgDetails.class);
                MsgEntity.ItemsBean msgEntity= (MsgEntity.ItemsBean) adapter.getData().get(position);
                intent2.putExtra("isRead",msgEntity.isIsRead());
                intent2.putExtra("id",msgEntity.getId());
                intent2.putExtra("title",msgEntity.getTitle());
                intent2.putExtra("content",msgEntity.getContent());
                intent2.putExtra("pushTime",msgEntity.getPushTime());
                iViewHome.startNextAc(intent2,1);
                msgEntity.setIsRead(true);
                adapter.notifyItemChanged(position);
                iViewHome.allMsgRead();
                break;
            case R.id.text_like:
                likeClick(adapter,view,position);
                break;
            case R.id.text_watch:
                onItemClick(adapter,view,position);
                break;
            case R.id.img_video:
            case R.id.img_video_play:
                playMusic();
                break;
        }
    }


    private void playMusic(){
    //    if (view.getId()==R.id.img_video_play||view.getId()==R.id.img_video){
        User user1=SharePreferenceUtil.getObject(MyApp.getInstance().getApplicationContext(),User.class);
        if (user1==null||user1.getAccessToken()==null||user1.getAccessToken().length()<1){
            iViewHome.startNextAc(new Intent(iViewHome.getContext(),LoginAc.class));
            return;
        }else {
            if (!childYiShuoEntity.isIsFree()&&!user.isVip()){
                showMsg("本条需要VIP,请充值");
                iViewHome.startNextAc(new Intent(iViewHome.getContext(),PayAc.class));
                return;
            }
        }

        User localUser=SharePreferenceUtil.getObject(iViewHome.getContext(),User.class);
        if (NetUtils.isMobileNetWork(iViewHome.getContext())&&!localUser.isListen()){
            Toast.makeText(iViewHome.getContext(),"您已设置流量模式禁止收听",Toast.LENGTH_SHORT).show();
            return;
        }
        MusicUtil.getInstance().setMusicTitle(childYiShuoEntity.getTitle());
        MusicUtil.getInstance().setMusicPic(Constant.BASE_URL+childYiShuoEntity.getUrl());
        MusicUtil.getInstance().sendStartEvent();
        user.setSayId(childYiShuoEntity.getId()+"");
        say_watch(user);
        MusicUtil.getInstance().sendStartEvent();
    }

    private void likeClick(BaseQuickAdapter adapter,View view,int position){
        switch (contentType) {
            case Constant.TAB_TYPE_SAY_WACTH:
                boolean operType=childYiShuoEntity.getLikeCountActive()==0;
                user.setSayId(childYiShuoEntity.getId()+"");
                user.setOperType(operType);
                user.setOrderType("1");
                like_doLike(user);
                break;
            case Constant.TAB_TYPE_SAY_LIKE:
                user.setSayId(childYiShuoEntity.getId()+"");
                user.setOperType(false);
                user.setOrderType("1");
                like_doLike(user);
                adapter.getData().remove(childYiShuoEntity);
                adapter.notifyItemRemoved(position);
                break;
            case Constant.TAB_TYPE_LIKE:
                user.setSayId(childYiShuoEntity.getId()+"");
                user.setOperType(false);
                user.setOrderType("2");
                like_doLike(user);
                adapter.getData().remove(childYiShuoEntity);;
                adapter.notifyItemRemoved(position);
                break;
        }
    }



    private void showMsg(String msg){
        Toast.makeText(iViewHome.getContext(),msg,Toast.LENGTH_SHORT).show();
    }

    private void deleteMsg(BaseQuickAdapter adapter ,int position){
        MsgEntity.ItemsBean itemsBean= (MsgEntity.ItemsBean) adapter.getData().get(position);
        adapter.getData().remove(itemsBean);
        adapter.notifyItemRemoved(position);
        user.setSayId(itemsBean.getId()+"");
        pushMessage_delete(user);
        iViewHome.allMsgRead();
    }


    /********
     * 观看接口
     * @param v
     * @param <V>
     */
    @Override
    public <V> void say_watch(V v) {
        super.say_watch(v);
        iService=new ImpDoWatch();
        iService.getObject(this,v);
    }

    @Override
    public <V> void like_doLike(V v) {
        super.like_doLike(v);
        iService=new ImpDoLike();
        iService.getObject(this,user);
    }


    @Override
    public <V> void pushMessage_delete(V v) {
        super.pushMessage_delete(v);
        iService=new ImpMsgDelete();
        iService.getObject(v);
    }



}
